// 提交回复
function post() {
    let postId = $("#postId").val();
    let description = $("#description").val();
    let plainText = $("#plainText").val();
    comment2target(postId, 1, description,plainText);
}

function comment2target(targetId, type,content,plainText) {
    if(!content || content.trim() === ""){
        alert("回复内容不能为空");
        return;
    }
    $.ajax({
        type: "POST",
        url: "/comment",
        contentType: "application/json",
        data: JSON.stringify({
            "plainText":plainText,
            "parentId":targetId,
            "content":content,
            type: type
        }),
        success:function (response) {
            if(response.code === "2000"){
                window.location.reload();
            }else if(response.code === "2003"){
                let isAccepted= confirm(response.message);
                if(isAccepted){
                    window.sessionStorage.setItem("redirectUrl",window.location.href);
                    window.location.replace("http://localhost:8080/login")
                }

            } else {
                alert(response.message);
            }
        },
        dataType:"json"
    })
}
//提交二级回复
function comment(e) {
    let commentId = e.getAttribute("data-id");
    let content = $("#input-" + commentId).val();
    let plainText = content;
    comment2target(commentId, 2,content,plainText);
}
//展开二级评论
function collapseComments(e) {
    let id = e.getAttribute("data-id");
    let comments = $("#comment-" + id);
    let collapse = e.getAttribute("data-collapse");

    if (collapse) {
        e.removeAttribute("data-collapse");
    } else {
        let subCommentContainer = $("#comment-" + id);
        if (subCommentContainer.children().length !== 1) {
            e.setAttribute("data-collapse", "in");
        } else {
            $.getJSON("/comment/" + id, function(data) {
                $.each(data.data.reverse(), function(index, comment) {
                    // 创建媒体左侧（头像链接）
                    let mediaLeftElement = $("<div/>", {
                        "class": "media-left"
                    }).append(
                        $("<a/>", {
                            "href": "/user/" + comment.user.id
                        }).append(
                            $("<img/>", {
                                "class": "face-m rounded",
                                "src": comment.user.avatarUrl
                            })
                        )
                    );
                    // 创建删除按钮（如果是所有者）
                    let deleteButton = '';
                    if (comment.owner) {
                        deleteButton = $("<a/>", {
                            "class": "post-menu float-md-left",
                            "onclick": "deleteComment('" + comment.id + "')",
                            "html": '<svg class="bi bi-trash" width="1em" height="1em"><path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0V6z"/><path fill-rule="evenodd" d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1v1zM4.118 4L4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4H4.118zM2.5 3V2h11v1h-11z"/></svg>删除'
                        });
                    }

                    // 创建媒体主体内容
                    let mediaBodyElement = $("<div/>", {
                        "class": "media-body body-margin"
                    }).append(
                        $("<a/>", {
                            "href": "/user/" + comment.user.id,
                            "class": "media-heading href mt-0",
                            "html": comment.user.nickname
                        }),
                        $("<div/>", {
                            "html": comment.content
                        }),
                        $("<div/>", {
                            "class": "menu"
                        }).append(
                            $("<span/>", {
                                "class": "float-right",
                                "html": moment(comment.gmtCreate).format('YYYY-MM-DD')
                            }),
                            deleteButton
                        )
                    );
                    // 组合媒体元素
                    let mediaElement = $("<div/>", {
                        "class": "media"
                    }).append(mediaLeftElement).append(mediaBodyElement);

                    // 创建评论元素
                    let commentElement = $("<div/>", {
                        "class": "comment"
                    }).append(mediaElement);

                    subCommentContainer.prepend(commentElement);
                });
                e.setAttribute("data-collapse", "in");
            });
        }
    }
    comments.toggleClass("collapse");
    e.classList.toggle("active");
}
function deleteComment(commentId) {
    if (confirm('确定要删除这条评论吗？')) {
        $.ajax({
            url: '/comment/' + commentId,
            type: 'DELETE',
            success: function(response) {
                if (response.code === "2000") {
                    // 找到并移除对应的评论元素
                    $('[data-id="' + commentId + '"]').closest('.comment').remove();
                    // 或者可以重新加载页面
                    window.location.reload();
                } else {
                    alert(response.message);
                }
            },
            error: function(xhr) {
                alert('删除失败: ' + xhr.responseJSON.message);
            }
        });
    }
}
function selectTag(e){
    let value = e.getAttribute("data-tag");
    let previous = $("#tag").val();
    if(previous.indexOf(value) === -1){
        if(previous){
            $("#tag").val(previous + ',' + value);
        }else {
            $("#tag").val(value);
        }
    }
}

$(document).ready(function() {
    // 鼠标进入导航项或下拉菜单时显示
    $('.nav-item.dropdown').hover(
        function() {
            $(this).find('.dropdown-menu').stop(true, true).slideDown(200);
        },
        function() {
            $(this).find('.dropdown-menu').stop(true, true).slideUp(200);
        }
    );

    // 防止鼠标离开导航项但还在下拉菜单时立即隐藏
    $('.dropdown-menu').hover(
        function() {
            $(this).stop(true, true).show();
        },
        function() {
            $(this).stop(true, true).hide();
        }
    );
});

function deletePost(postId) {
    // 获取当前用户ID（可以从页面隐藏字段或全局变量获取）
    const userId = $('#userId').val();
    const creator = $('#creator').val();
    if (userId !== creator) {
        alert('只能删除自己的内容');
        window.location.reload();
    }
    if (confirm('确定要删除这条内容吗？')) {

        $.ajax({
            url: '/delete/' + postId,
            type: 'DELETE',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="_csrf"]').attr('content'),
                'X-Requested-With': 'XMLHttpRequest'
            },
            data: {
                userId:userId,
                creator:creator,
            },
            success: function(data) {
                $('[data-id="' + postId + '"]').closest('.post-item').remove();
                alert('删除成功');
                window.location.replace("/");
            },
            error: function(xhr) {
                if (xhr.status === 403) {
                    alert('权限不足：只能删除自己的内容');
                } else {
                    alert('删除失败: ' + xhr.responseJSON.message);
                }
            }
        });
    }
}
function markAllAsRead() {
    if (confirm('确定将所有通知标记为已读吗？')) {
        $.ajax({
            url: '/notification/markAllAsRead',
            type: 'POST',
            success: function(response) {
                if (response.code === "2000") {
                    // 更新页面状态
                    $('.badge-danger').remove();
                    // 可选：刷新页面
                    window.location.reload();
                } else {
                    alert(response.message);
                }
            },
            error: function(xhr) {
                alert('操作失败: ' + xhr.responseJSON.message);
            }
        });
    }
}

// 全部删除功能
function deleteAllNotifications() {
    if (confirm('确定删除所有通知吗？此操作不可恢复！')) {
        $.ajax({
            url: '/notification/deleteAll',
            type: 'POST',
            success: function(response) {
                if (response.code === "2000") {
                    // 刷新页面
                    window.location.reload();
                } else {
                    alert(response.message);
                }
            },
            error: function(xhr) {
                alert('操作失败: ' + xhr.responseJSON.message);
            }
        });
    }
}
//点赞
$(document).on('click', '.like-btn', function() {
    const $btn = $(this);
    const targetId = $btn.data('id');
    const type = $btn.data('type');
    $.ajax({
        url: '/like',
        type: 'POST',
        data:{
            targetId: targetId,
            type: type
        },
        success: function(response) {
            if (response.code === "2000") {
                const $count = $btn.find('.like-count');
                const currentCount = parseInt($count.text());
                const isLiked = $btn.hasClass('liked');

                // 更新UI
                $btn.toggleClass('liked');
                $count.text(isLiked ? currentCount - 1 : currentCount + 1);

                // 可选：添加动画效果
                $btn.css('transform', 'scale(1.2)');
                setTimeout(() => {
                    $btn.css('transform', 'scale(1)');
                }, 300);
            } else if (response.code === "2003") {
                // 未登录处理
                const isAccepted = confirm(response.message);
                if (isAccepted) {
                    window.sessionStorage.setItem("redirectUrl", window.location.href);
                    window.location.replace("/login");
                }
            } else {
                alert(response.message);
            }
        },
        error: function(xhr) {
            alert('操作失败: ' + xhr.responseJSON.message);
        }
    });
});
// 全局未读消息计数刷新
function refreshUnreadCount() {
    $.ajax({
        url: '/messages/unread-count',
        method: 'GET',
        success: function(data) {
            // 确保处理响应数据结构一致
            const count = (data.code === "2000") ? data.data : 0;
            const $badge = $('#message-badge');

            // 双重检查元素是否存在
            if ($badge.length) {
                $badge.toggle(count > 0).text(count);
            } else {
                console.warn('未找到消息徽章元素');
            }
        },
        error: function(xhr) {
            console.error('获取未读通知数失败:', xhr.statusText);
        }
    });
}
function startNotificationPolling() {
    $.ajax({
        url: '/notifications/unread-count',
        method: 'GET',
        success: function(data) {
            // 确保处理响应数据结构一致
            const count = (data.code === "2000") ? data.data : 0;
            const $badge = $('#notification-badge');

            // 双重检查元素是否存在
            if ($badge.length) {
                $badge.toggle(count > 0).text(count);
            } else {
                console.warn('未找到消息徽章元素');
            }
        },
        error: function(xhr) {
            console.error('获取未读消息数失败:', xhr.statusText);
        }
    });
}
// 页面加载时立即执行
$(document).ready(function() {
    refreshUnreadCount();
    startNotificationPolling()

    // 设置30秒轮询
    setInterval(refreshUnreadCount, 30000);
    setInterval(startNotificationPolling, 30000);

});

// 全局消息发送成功后的回调
$(document).on('message:sent', function() {
    refreshUnreadCount();
});